package top.tangyh.lamp.care.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.tangyh.basic.base.R;
import top.tangyh.basic.exception.BizException;
import top.tangyh.basic.interfaces.echo.EchoService;
import top.tangyh.basic.base.controller.SuperController;
import top.tangyh.basic.utils.DateUtils;
import top.tangyh.lamp.care.service.BCarePgRecordService;
import top.tangyh.lamp.care.entity.BCarePgRecord;
import top.tangyh.lamp.care.vo.result.CarePgRecordTypeVO;
import top.tangyh.lamp.care.vo.save.BCarePgRecordSaveVO;
import top.tangyh.lamp.care.vo.update.BCarePgRecordUpdateVO;
import top.tangyh.lamp.care.vo.result.BCarePgRecordResultVO;
import top.tangyh.lamp.care.vo.query.BCarePgRecordPageQuery;
import top.tangyh.lamp.common.utils.ConvertUtil;
import top.tangyh.lamp.common.utils.PDateUtils;

import javax.validation.Valid;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 前端控制器
 * 护理入科评估表
 * </p>
 *
 * @author zqb
 * @date 2024-07-26 10:31:53
 * @create [2024-07-26 10:31:53] [zqb]
 */
@Slf4j
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/carePgRecord")
@Tag(name = "系统：入院评估")
public class BCarePgRecordController {

//    extends SuperController<BCarePgRecordService, Long, BCarePgRecord
//            , BCarePgRecordSaveVO, BCarePgRecordUpdateVO, BCarePgRecordPageQuery, BCarePgRecordResultVO>
//    private final EchoService echoService;
//    @Override
//    public EchoService getEchoService() {
//        return echoService;
//    }


    private final BCarePgRecordService bCarePgRecordService;

    @Operation(summary = "新增入院评估")
    @PostMapping("/add")
    public R add(@RequestBody BCarePgRecordSaveVO carePgRecordVo) {

        //访问权限验证
//        if(yxPgRecordTemporaryService.check(carePgRecordVo.getHospitalNumber(),carePgRecordVo.getType()) == false){
//            return R.error(SysCodeEnum.PERMISSION_DENIED);
//        }
        carePgRecordVo.setPfTime(DateUtils.getDateTimeOfTimestamp(carePgRecordVo.getPftimeLong()));
        BCarePgRecord po = ConvertUtil.convert(carePgRecordVo, BCarePgRecord.class);
        bCarePgRecordService.checkPgByPfTime(po);

        BCarePgRecord result = bCarePgRecordService.save(po);
        if (null != result.getId()) {
            return R.success(result.getId());
        } else {
            return R.fail("新增失败");
        }
//        if(null!=result.getId()){
//            yxPgRecordTemporaryService.cleanPgRedis(carePgRecordVo.getHospitalNumber(),carePgRecordVo.getType());
//            return R.success();
//        }
//        else{
//            return R.error();
//        }
    }

    @Operation(summary = "更新入院评估")
    @PutMapping("update/carePgRecord")
    public R updateById(@Parameter(description = "入院评估对象") @Valid @RequestBody BCarePgRecordUpdateVO carePgRecordVo) {
        //访问权限验证
//        if(yxPgRecordTemporaryService.check(carePgRecordVo.getHospitalNumber(),carePgRecordVo.getType()) == false){
//            return R.error(SysCodeEnum.PERMISSION_DENIED);
//        }

        BCarePgRecord po = ConvertUtil.convert(carePgRecordVo, BCarePgRecord.class);
        //是否本人修改 验证
//        if(null != po.getId()){
//            YxCarePgRecordPO old = yxCarePgRecordService.getById(po.getId());
//            if(null != SecurityUtil.checkRecordAuth(old.getCreateBy() ,old.getUpdateBy())){
//                throw new BizException(SecurityUtil.checkRecordAuth(old.getCreateBy() ,old.getUpdateBy()));
//            }
//        }
        po.setPfTime(PDateUtils.getDateTimeOfTimestamp(carePgRecordVo.getPftimeLong()));
        BCarePgRecord result = bCarePgRecordService.updateById(po);
        return R.success();
//        if (result) {
//            yxPgRecordTemporaryService.cleanPgRedis(carePgRecordVo.getHospitalNumber(),carePgRecordVo.getType());
//            return R.success();
//        } else {
//            return R.error();
//        }
    }

    @Operation(summary = "根据ID查询入院评估详情")
    @GetMapping(value = "/carePgRecord/{id}")
    public R<BCarePgRecordResultVO> getCarePgRecord(@PathVariable("id") Long id) {
        BCarePgRecord po = bCarePgRecordService.getById(id);
//        po.setPftimeLong(PDateUtils.getTimestampOfDateTime(po.getPfTime()));
        Optional.ofNullable(po)
                .map(poObj -> poObj.getPfTime())
                .ifPresent(pfTime -> po.setPftimeLong(PDateUtils.getTimestampOfDateTime(pfTime)));

        BCarePgRecordResultVO bCarePgRecordResultVO = ConvertUtil.convert(po, BCarePgRecordResultVO.class);
        return R.success(bCarePgRecordResultVO);
    }

    /**
     * 查询护理入科评估列表 按照type分组
     */
    @GetMapping(value = "/list")
    @Operation(summary = "查询护理入科评估列表-按照type分组")
    public R<List<CarePgRecordTypeVO>> list(@Parameter(description = "病人识别号", required = true) @RequestParam String patientIdent,
                                            @Parameter(description = "类型") @RequestParam(required = false) Integer type,
                                            @Parameter(description = "入科时间") @RequestParam(required = false) Long rkTime,
                                            @Parameter(description = "出科时间") @RequestParam(required = false) Long ckTime) {
        List<CarePgRecordTypeVO> list_result = new ArrayList<>();
        List<BCarePgRecord> list = bCarePgRecordService.listCarePgRecordByPatientIdent(patientIdent, type, rkTime, ckTime);
        for (int i = 0; i < list.size(); i++) {
            CarePgRecordTypeVO vo = new CarePgRecordTypeVO();
            BCarePgRecord record = list.get(i);
            // 将 pfTime 转换为时间戳并设置到 pftimeLong
            if (record.getPfTime() != null) {
                record.setPftimeLong(record.getPfTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
            }

            vo.setPo(record);
            vo.setType(record.getType());
            list_result.add(vo);
        }
        return R.success(list_result);
    }

    @DeleteMapping("/deleteById")
    @Operation(summary = "删除")
    public R<Boolean> delete(@RequestParam Long id) {
        //验证本人是否能修改  新系统等需求调研确认后再决定做不做这个验证
//        if (null != id) {
//            BCarePgRecord old = bCarePgRecordService.getById(id);
//            if (null != SecurityUtil.checkRecordAuth(old.getCreateBy(), old.getUpdateBy())) {
//                throw new BadRequestException(SecurityUtil.checkRecordAuth(old.getCreateBy(), old.getUpdateBy()));
//            }
//
//        }

        //相关redis 清理 新系统等需求调研确认后再决定做不做这个功能
//        if (yxPgRecordTemporaryService.checkDeleteById(id) == false) {
//            return R.error(false);
//        }
        List<Long> ids = new ArrayList<>();
        ids.add(id);
        return R.success(bCarePgRecordService.removeByIds(ids));
    }
}


